package com.xq.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xq.base.ResponseResult;
//import com.xq.entity.UserInfo;
import com.xq.entity.UserInfo;
import com.xq.mapper.UserInfoMapper;
import com.xq.service.IdentityService;
import com.xq.service.UserService;
import com.xq.service.tesk.IdentityAuthTask;
import com.xq.service.tesk.LiveAuthTask;
import com.xq.service.tesk.UploadTask;
import lombok.extern.log4j.Log4j2;
import org.redisson.api.RBucket;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.security.UnresolvedPermission;
import java.util.Base64;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Log4j2
@RestController
@CrossOrigin
public class IdentityController {

    private ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(32,52,1L, TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(200));

    @Autowired
    private IdentityService identityService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private RedisTemplate redisTemplate;



    @RequestMapping("/identityAuth")
   public ResponseResult identityAuth(String name,String cardId,
                                       @RequestParam("frontImage") MultipartFile frontImage,
                                      @RequestParam("backImage") MultipartFile backImage,
                                      @RequestParam("liveImage") MultipartFile liveImage){


        Long userId = 1L;
        //user_identity_lock
        RLock lock = redissonClient.getLock("user_identity_lock_" + userId);
        boolean flag = lock.tryLock();
        if(!flag){
            return ResponseResult.error(402,"您正在身份认证中");
        }
        lock.lock(6,TimeUnit.SECONDS);
      /* //调用身份认证接口
        String baseFrontImage = "";
        try {
             if(frontImage!=null){
                 baseFrontImage = Base64.getEncoder().encodeToString(frontImage.getBytes());
             }

        log.info("日志输出:baseb4:"+baseFrontImage);
        String str = identityService.identityAuth(name,cardId,baseFrontImage);
        log.info("身份认证结果::"+str);
        JSONObject json = JSON.parseObject(str);
        Integer code = json.getInteger("code");
        if(code!=0){
            return ResponseResult.error(400,"身份认证失败");
        }
        JSONObject data = json.getJSONObject("data");
        Integer score = data.getInteger("score");
        *//*if(score<75){
            return ResponseResult.error(400,"身份认证分数太小");
        }*//*

        String base64LiveImage ="";
        if(liveImage!=null){
            base64LiveImage = Base64.getEncoder().encodeToString(liveImage.getBytes());
        }
            //调用活体接口
        String str2 = identityService.liveAuth(base64LiveImage);
        log.info("活体对比结果::"+str2);
            JSONObject json2 = JSON.parseObject(str2);
            Integer code2 = json2.getInteger("code");
            if(code2!=0){
                return ResponseResult.error(400,"活体认证失败");
            }
            JSONObject data2 = json.getJSONObject("data");
            Integer score2 = data2.getInteger("score");
            *//*if(score2<75){
                return ResponseResult.error(400,"活体分数太小");
            }*//*


            //上传到文件服务器
            Thread.sleep(2000);

            //修改数据库姓名和身份证号*/

/*
        try {

           long startTime = System.currentTimeMillis();
            //1
            String baseFrontImage = Base64.getEncoder().encodeToString(frontImage.getBytes());
            //构建任务
            IdentityAuthTask identityAuthTask = new IdentityAuthTask(name,cardId,baseFrontImage,identityService);
            //提交任务
            Future<Boolean> identityAuthFuture = threadPoolExecutor.submit(identityAuthTask);

            //2
            String base64LiveImage = Base64.getEncoder().encodeToString(liveImage.getBytes());
            //构建任务
            LiveAuthTask liveAuthTask = new LiveAuthTask(base64LiveImage,identityService);
            //提交任务
            Future<Boolean> liveAuthFuture = threadPoolExecutor.submit(liveAuthTask);

            //3
            //构建任务
            UploadTask uploadTask = new UploadTask(liveImage.getBytes(),frontImage.getBytes(),
                   backImage.getBytes(), identityService);
            //提交任务
            Future<Map<String,String>> uploadFuture = threadPoolExecutor.submit(uploadTask);

            //使用Future的get方法会当前线程阻塞
            Boolean identityFlag = identityAuthFuture.get();
            System.out.println("identityFlag:"+identityFlag);
            Boolean liveFlag = liveAuthFuture.get();
            System.out.println("liveFlag:"+liveFlag);
            Map<String,String> uploadFlag = uploadFuture.get();
            System.out.println("uploadFlag:"+JSON.toJSONString(uploadFlag));
            long endTime = System.currentTimeMillis();
            log.info("时间:"+(endTime-startTime));
            //获取任务的结果，调用get会阻塞线程，知道当前任务执行完
            //Boolean identityFlag = identityAuthFuture.get();
            if(identityFlag && liveFlag && uploadFlag!=null && uploadFlag.size()>0){
                //正常情况下userId都是从seesion或者安全认证框架里面获取的
                Long userIds=1L;
                UserInfo userInfo = new UserInfo();
                userInfo.setId(userIds);
                userInfo.setUserName(name);
                userInfo.setUserCardId(cardId);
                userInfo.setLinkFront(uploadFlag.get("frontImageUrl"));
                userInfo.setLinkBack(uploadFlag.get("backImageUrl"));
                userInfo.setLinkHand(uploadFlag.get("liveImageUrl"));
                userService.updateByPrimaryKey(userInfo);
                return ResponseResult.success();
            }else {
                return ResponseResult.error(402,"身份认证失败");
            }


        }catch (Exception ex){
            ex.printStackTrace();
        }finally {

        if(lock.isLocked()){
            if(lock.isHeldByCurrentThread()){
                lock.unlock();
            }
        }

        }*/
        return ResponseResult.success();
    }
}
